'use strict';

const BaseController = require('../base');

class UserCouponController extends BaseController {
  static get serviceName() {
    return 'business.userCoupon';
  }

  formatOrder() {
    return [
      ['status', 'asc'],
       ['coupon_id', 'desc'],
    ]
  }

  // 查询用户优惠券使用情况
  async getUserCoupons() {
    const { ctx } = this;
    const { user_id, status, coupon_id } = ctx.query;
    
    const where = {};
    if (user_id) where.user_id = user_id;
    if (status !== undefined) where.status = status;
    if (coupon_id) where.coupon_id = coupon_id;
    
    const result = await this.service.find({
      where,
      include: [
        { model: this.ctx.model.Business.Coupon, as: 'coupon' },
        { model: this.ctx.model.Business.User, as: 'user' },
        { model: this.ctx.model.Business.Order, as: 'order' }
      ],
      order: [['create_time', 'DESC']]
    });
    
    ctx.success(result);
  }

  // 查询用户可用优惠券
  async getAvailableCoupons() {
    const { ctx } = this;
    const { user_id, amount } = ctx.query;
    
    if (!user_id) {
      ctx.error(400, '用户ID不能为空');
      return;
    }
    
    const result = await this.service.find({
      where: {
        user_id,
        status: 0, // 未使用
        expire_time: {
          [this.ctx.model.Sequelize.Op.gt]: new Date() // 未过期
        }
      },
      include: [
        { model: this.ctx.model.Business.Coupon, as: 'coupon' }
      ],
      order: [['create_time', 'DESC']]
    });
    
    // 如果提供了订单金额，过滤出可用的优惠券
    if (amount) {
      const availableCoupons = result.filter(item => {
        const coupon = item.coupon;
        if (!coupon) return false;
        
        // 检查使用门槛
        if (coupon.min_amount && amount < coupon.min_amount) {
          return false;
        }
        
        return true;
      });
      
      ctx.success(availableCoupons);
    } else {
      ctx.success(result);
    }
  }
}

module.exports = UserCouponController;
